package com.moyun.finance.service;

import com.moyun.finance.entity.*;
import com.moyun.finance.repository.OrgCompanyRepository;
import com.moyun.finance.repository.OrgRoleRepository;
import com.moyun.finance.repository.OrgRoleUserMidRepository;
import com.moyun.finance.repository.OrgUserRepository;
import com.moyun.finance.utils.BaseUtil;
import com.moyun.finance.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class OrgCompanyService {
    @Autowired
    OrgCompanyRepository odr;
    @Autowired
    OrgUserRepository our;
    @Autowired
    OrgRoleRepository orr;
    @Autowired
    OrgRoleUserMidRepository orumr;

    public Response save(OrgCompany company, HttpServletRequest request){
        OrgCompany findDept = odr.findByFolderName(company.getFolderName());
//        OrgUser user = (OrgUser) request.getSession().getAttribute("loginUser");
        OrgUser user = UserUtil.getLoginUser(request);
        if(findDept != null){
            return new Response("该公司已注册!",false);
        }
        company.setId(BaseUtil.uuid());
        company.setCreatedUserid(user.getId());
        odr.save(company);
        //新建一个该公司下的主管理员角色
        OrgRole role = new OrgRole();
        role.setId(BaseUtil.uuid());
        role.setCompanyId(company.getId());
        role.setRoleName("主管理员");
        orr.save(role);
        //为创始人添加公司ID
        user.setCompanyId(company.getId());
        our.save(user);
        //默认给创始人主管理员角色
        OrgRoleUserMid orum = new OrgRoleUserMid();
        orum.setId(BaseUtil.uuid());
        orum.setRoleId(role.getId());
        orum.setUserId(user.getId());
        orumr.save(orum);
        return new Response("注册公司成功!",true);
    }

    public Response update(OrgCompany c){
        odr.save(c);
        return new Response("公司信息修改成功!",true);
    }

    public OrgCompany find(String companyId){
        OrgCompany orgCompany = odr.findById(companyId).orElse(null);
        return orgCompany;
    }
}
